package com.sevenluo.netty.learn.client;

import com.sevenluo.netty.learn.client.codec.OrderFrameDecoder;
import com.sevenluo.netty.learn.client.codec.OrderFrameEncoder;
import com.sevenluo.netty.learn.client.codec.OrderProtocolDecoder;
import com.sevenluo.netty.learn.client.codec.OrderProtocolEncoder;
import com.sevenluo.netty.learn.client.handler.ClientIdleCheckHandler;
import com.sevenluo.netty.learn.common.RequestMessage;
import com.sevenluo.netty.learn.common.auth.AuthOperation;
import com.sevenluo.netty.learn.common.order.OrderOperation;
import com.sevenluo.netty.learn.client.handler.KeepaliveHandler;
import com.sevenluo.netty.learn.util.IdUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

/**
 * @author: 程序员七哥
 * @date: 2022-01-29
 * @description: 客户端启动类
 */
public class ClientV0 {

    public static void main(String[] args) throws Exception {

        NioEventLoopGroup group = new NioEventLoopGroup();
        try {

            Bootstrap bootstrap = new Bootstrap();

            KeepaliveHandler keepaliveHandler = new KeepaliveHandler();

            // 客户端 ssl 认证，不需要证书，服务端单向验证
            SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
            SslContext sslContext = sslContextBuilder.build();

            bootstrap.channel(NioSocketChannel.class)
                    .group(group)
                    // 设置客户端连接超时时间
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,10*1000)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 空闲监测
                            pipeline.addLast(new ClientIdleCheckHandler());

                            // 加入 ssl 验证
                            pipeline.addLast("ssl", sslContext.newHandler(ch.alloc()));

                            pipeline.addLast(new OrderFrameDecoder());
                            pipeline.addLast(new OrderFrameEncoder());

                            pipeline.addLast(new OrderProtocolEncoder());
                            pipeline.addLast(new OrderProtocolDecoder());

                            // keepalive 保持连接不中断
                            pipeline.addLast(keepaliveHandler);

                            pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080).sync();

            //先发送授权认证消息
            RequestMessage authMessage = new RequestMessage(IdUtil.nextId(), new AuthOperation("admin", "admin"));
            channelFuture.channel().writeAndFlush(authMessage);

            RequestMessage requestMessage = new RequestMessage(IdUtil.nextId(), new OrderOperation(1001, "tudou"));
            // 模拟制造内存泄漏，因为必须发生 GC 才能被检测到，这里发送 1w 条消息
            // for (int i = 0; i < 10; i++) {
            //     channelFuture.channel().writeAndFlush(requestMessage);
            // }
            channelFuture.channel().writeAndFlush(requestMessage);


            channelFuture.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully();
        }
    }

}
